package com.wanhe.mealbookmodule.views;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.orhanobut.logger.Logger;
import com.wanhe.base.Const;
import com.wanhe.base.model.base.Dish;
import com.wanhe.base.model.disgn.DSFile;
import com.wanhe.base.model.disgn.PageViewModel;
import com.wanhe.base.model.disgn.ViewItem;
import com.wanhe.base.model.holder.DishHolder;
import com.wanhe.base.model.holder.FileHolder;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.StringFileUtil;
import com.wanhe.mealbookmodule.R;
import com.wanhe.mealbookmodule.adapter.MealBookItemsAdapter;
import com.wanhe.viewconf.ViewCreator;
import com.wanhe.viewconf.adapter.BaseMenuPageItemAdapter;
import com.wanhe.viewconf.generator.IViewGenerator;
import com.wanhe.viewconf.views.child.BaseXYView;
import com.wanhe.viewconf.views.child.MealBookChildItemView;
import com.wanhe.viewconf.views.group.CoordinateViewGroup;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutionException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by cdj on 2017/6/22.
 */

public class MealBookPageItemView extends FrameLayout {
	public static final String	TAG	= "MealBookPageItemView";

	private CoordinateViewGroup	mealItemsLayout;
	private ImageView			mealImageView;
	private int					mPageIndex;
	private PageViewModel		mViewModel;

	public MealBookPageItemView(Context context) {
		this(context, null);
	}

	public int getTypeID() {
		return mViewModel.getTid();
	}

	public MealBookPageItemView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		LayoutInflater.from(context).inflate(R.layout.meal_book_page_layout, this);
		mealImageView = (ImageView) findViewById(R.id.iv_meal_book_bg);
		mealItemsLayout = (CoordinateViewGroup) findViewById(R.id.cvg_meal_book_items);
	}

	public void initData(PageViewModel viewModel) {
		this.mViewModel = viewModel;
		// String imageUrl = getHostAddress() + "/GetImage" + "/menu_image/" +
		// "%s";
		// imageUrl = String.format(imageUrl,
		// viewModel.getImage().getFileName());
		DSFile file = FileHolder.getInstance().get(viewModel.getImage());
		if (!ObjectUtil.checkObject(file)){
			Logger.t(TAG).e("加载背景图片失败，文件找不到  %d", viewModel.getImage());
			return;
		}
		File gifFile = StringFileUtil.isFileExists(Const.imageBaseUrl,
				file.getFileName());
		if (ObjectUtil.checkObject(gifFile)) {
			String imageUrl = Const.imageBaseUrl + gifFile.getName();
			loadImage(imageUrl);
		}

	}

	public class BitmapInfo {
		public String	url;
		public int		width;
		public int		height;
	}

	private void loadImage(final String imageUrl) {
		Observable.create(new ObservableOnSubscribe<BitmapInfo>() {
			@Override
			public void subscribe(@NonNull ObservableEmitter<BitmapInfo> e) throws Exception {
				FutureTarget<File> future = Glide.with(getContext()).load(imageUrl).downloadOnly(30,
						30);
				try {
					File cacheFile = future.get();
					String path = cacheFile.getAbsolutePath();
					BitmapFactory.Options options = new BitmapFactory.Options();
					// 设置为true,表示解析Bitmap对象，该对象不占内存
					options.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(path, options);
					int bitmapWidth = options.outWidth;
					int bitmapHeight = options.outHeight;
					if (bitmapWidth <= 1540 && bitmapHeight <= 2050) {
						BitmapInfo info = new BitmapInfo();
						info.url = imageUrl;
						info.width = bitmapWidth;
						info.height = bitmapHeight;
						e.onNext(info);
					} else {
						e.onError(new Throwable("图片太大"));
					}
				} catch (InterruptedException err) {
					err.printStackTrace();
				} catch (ExecutionException err) {
					err.printStackTrace();
				}
			}
		}).subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
				.observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber
															// 的回调发生在主线程
				.subscribe(new Observer<BitmapInfo>() {
					@Override
					public void onSubscribe(@NonNull Disposable d) {

					}

					@Override
					public void onNext(@NonNull BitmapInfo bitmapInfo) {
						// Glide 框架加载图片
						Glide.with(getContext()).load(bitmapInfo.url).error(R.drawable.error_img)
								.diskCacheStrategy(DiskCacheStrategy.SOURCE).override(600, 960)
								.into(target);
					}

					@Override
					public void onError(@NonNull Throwable e) {
						Glide.with(getContext()).load(R.drawable.error_img).into(target);
					}

					@Override
					public void onComplete() {

					}
				});
	}

	private SimpleTarget target = new SimpleTarget<GlideBitmapDrawable>() {
		@Override
		public void onLoadStarted(Drawable placeholder) {
			// showProcess();
		}

		@Override
		public void onResourceReady(GlideBitmapDrawable drawable, GlideAnimation glideAnimation) {
			setItem(drawable);
		}

		@Override
		public void onLoadFailed(Exception e, Drawable errorDrawable) {
			setItem(errorDrawable);
		}
	};

	private void setItem(Drawable bg) {
		float width = bg.getIntrinsicWidth();
		float height = bg.getIntrinsicHeight();
		mealImageView.setBackground(bg);
		mealItemsLayout.setRealScale(width / height);
		// hideProcess();
		// 在所有控件都添加都树结构中的时候在显示，一次性刷新，减少过度刷新
		initMealBookItems(this.mViewModel);
	}

	public void initPageData() {
		this.mealItemsLayout.initMealBookPage();
	}

	public void pausePage(){
		this.mealItemsLayout.pauseChildItems();
	}

	private void initMealBookItems(PageViewModel model) {
		MealBookItemsAdapter pagerAdapter = new MealBookItemsAdapter(getContext(),
				model.getItems());
		pagerAdapter.setPageIndex(mPageIndex);
		mealItemsLayout.setAdapter(pagerAdapter);
		mealItemsLayout.setVisibility(VISIBLE);
	}

	private String getHostAddress() {
		return "http://" + SPUtils.getIp() + ":" + SPUtils.getPort();
	}

	public void setPageIndex(int position) {
		this.mPageIndex = position;
	}

}
